package com.ruoyi.smartHighway.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.smartHighway.mapper.AppMapper;
import com.ruoyi.smartHighway.service.AutoSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lingjj
 * @ClassName AutoSyncServiceImpl
 * @description: 数据自动同步
 * @date 2024年11月06日
 * @version: 1.0
 */
@Service
public class AutoSyncServiceImpl implements AutoSyncService {

    private static Logger logger = LoggerFactory.getLogger(AutoSyncServiceImpl.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AppMapper appMapper;

    private String getBaiduToken() {
        String token = redisTemplate.opsForValue().get("baidu_token");
        if(token == null){
            String url = "http://172.31.255.80/ihs/apipartake/oauth/token";
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            requestBody.add("grant_type", "client_credentials");
            requestBody.add("scope", "fk-app");
            requestBody.add("client_id", "shuangyin-fokai");
            requestBody.add("client_secret", "NfndFlw8arvcBjZtmk07fAJSLsjZs3BG");
            // 发起 POST 请求
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.postForObject(url, requestBody, String.class);
            logger.info("Response: " + response);
            JSONObject jsonObject = JSON.parseObject(response);
            token = jsonObject.getString("access_token");
            logger.info("Response: " + response);
            // 输出响应
            redisTemplate.opsForValue().set("baidu_token",token,12, TimeUnit.HOURS);
        }
        return token;
    }

    @Override
    public void autoSyncEventInfo() {
        long time = System.currentTimeMillis();
        logger.info("佛开事件信息同步任务 start。。。。");

        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/event/page";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        Map<String,Object> queryMap = new HashMap<>();
//        {"beginTime":"2024-11-01 00:00:00","endTime":"2024-11-01 12:00:00","pageNumber":1,"pageSize":10000}
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime previousHourStart = now.minusHours(1).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime previousHourEnd = now.minusHours(1).withMinute(59).withSecond(59).withNano(999_999_999);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String beginTime = previousHourStart.format(formatter);
        String endTime = previousHourEnd.format(formatter);

        queryMap.put("beginTime",beginTime);
        queryMap.put("endTime",endTime);
        queryMap.put("pageNumber",1);
        queryMap.put("pageSize",10000);

        String requestBody = JSON.toJSONString(queryMap);
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, request, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONObject dataObject = jsonObject.getJSONObject("data");
            JSONArray itemArray = dataObject.getJSONArray("result");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> eventInfoList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> eventInfoItem = item.toJavaObject(Map.class);
                    eventInfoList.add(eventInfoItem);
                }
                appMapper.batchAddEventInfoList(eventInfoList);
            }
        }else {
            logger.info("佛开事件信息同步任务异常，response： " + response);
        }
        logger.info("佛开事件信息同步任务 end 用时： " + (System.currentTimeMillis()-time));
    }

    @Override
    public void autoSyncDeviceList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/device/getDeviceList";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);

        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> deviceList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> deviceItem = new HashMap<>();
                    deviceItem.put("alt",item.get("alt"));
                    deviceItem.put("deviceCode",item.get("deviceCode"));
                    deviceItem.put("deviceType",item.get("deviceType"));
                    deviceItem.put("deviceLocation",item.get("deviceLocation"));
                    deviceItem.put("deviceName",item.get("deviceName"));
                    deviceItem.put("deviceSn",item.get("deviceSn"));
                    deviceItem.put("lat",item.get("lat"));
                    deviceItem.put("lng",item.get("lng"));
                    deviceItem.put("stake",item.get("stake"));
                    deviceItem.put("status",item.get("status"));
                    deviceList.add(deviceItem);
                }
                appMapper.truncateDevice();
                appMapper.batchAddDevice(deviceList);
            }
        }
    }

    @Override
    public void autoSyncDeviceNum() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/device/getDeviceNum";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> deviceNumList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> deviceNumItem = new HashMap<>();
                    deviceNumItem.put("deviceType",item.get("deviceType"));
                    deviceNumItem.put("deviceNum",item.get("deviceNum"));
                    deviceNumItem.put("onlineDeviceNum",item.get("onlineDeviceNum"));
                    deviceNumItem.put("deviceRate",item.get("deviceRate"));
                    deviceNumList.add(deviceNumItem);
                }
                appMapper.truncateDeviceNum();
                appMapper.batchAddDeviceNum(deviceNumList);
            }
        }
    }

    @Override
    public void autoSyncFacilityList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/facility/getFacilityList";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> facilityList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> facilityItem = new HashMap<>();
                    facilityItem.put("alt",item.get("alt"));
                    facilityItem.put("facilityName",item.get("facilityName"));
                    facilityItem.put("facilityType",item.get("facilityType"));
                    facilityItem.put("stake",item.get("stake"));
                    facilityItem.put("direction",item.get("direction"));
                    facilityItem.put("roadName",item.get("roadName"));
                    facilityItem.put("lat",item.get("lat"));
                    facilityItem.put("lng",item.get("lng"));
                    facilityItem.put("centerPoint",item.get("centerPoint"));
                    facilityList.add(facilityItem);
                }
                appMapper.truncateFacilityList();
                appMapper.batchAddFacilityList(facilityList);
            }
        }
    }

    @Override
    public void autoSyncFacilityNum() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/facility/getFacilityNum";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONObject objectData = jsonObject.getJSONObject("data");
            Map<String,Object> facilityNumMap = new HashMap<>();
            facilityNumMap.put("gradeNum",objectData.get("gradeNum"));
            facilityNumMap.put("bridgeNum",objectData.get("bridgeNum"));
            facilityNumMap.put("monBridgeNum",objectData.get("monBridgeNum"));
            facilityNumMap.put("noMonBridgeNum",objectData.get("noMonBridgeNum"));

            appMapper.truncateFacilityNum();
            appMapper.addFacilityNum(facilityNumMap);
        }
    }

    @Override
    public void autoSyncBridgeGradeList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/facility/bridgeGradeList";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> bridgeGradeList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> bridgeGradeItem = new HashMap<>();
                    bridgeGradeItem.put("brdgeId",item.get("brdgeId"));
                    bridgeGradeItem.put("brdgeName",item.get("brdgeName"));
                    bridgeGradeItem.put("mqi",item.get("mqi"));
                    bridgeGradeItem.put("mqiGrade",item.get("mqiGrade"));
                    bridgeGradeList.add(bridgeGradeItem);
                }
                appMapper.truncateBridgeGradeList();
                appMapper.batchAddBridgeGradeList(bridgeGradeList);
            }
        }
    }

    @Override
    public void autoSyncBridgeInfoList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/facility/bridgeInfoList";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> bridgeInfoList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> bridgeInfoItem = new HashMap<>();
                    bridgeInfoItem.put("brdgeId",item.get("brdgeId"));
                    bridgeInfoItem.put("brdgeName",item.get("brdgeName"));
                    bridgeInfoItem.put("bridgeLength",item.get("bridgeLength"));
                    bridgeInfoItem.put("districtName",item.get("districtName"));
                    bridgeInfoItem.put("mqiGrade",item.get("mqiGrade"));

                    bridgeInfoItem.put("startStake",item.get("startStake"));
                    bridgeInfoItem.put("centerStake",item.get("centerStake"));
                    bridgeInfoItem.put("endStake",item.get("endStake"));
                    bridgeInfoItem.put("startLat",item.get("startLat"));
                    bridgeInfoItem.put("startLng",item.get("startLng"));

                    bridgeInfoItem.put("centerLat",item.get("centerLat"));
                    bridgeInfoItem.put("centerLng",item.get("centerLng"));
                    bridgeInfoItem.put("endLat",item.get("endLat"));
                    bridgeInfoItem.put("endLng",item.get("endLng"));
                    bridgeInfoItem.put("alt",item.get("alt"));

                    bridgeInfoList.add(bridgeInfoItem);
                }
                appMapper.truncateBridgeInfoList();
                appMapper.batchAddBridgeInfoList(bridgeInfoList);
            }
        }
    }

    @Override
    public void autoSyncRoadGradeList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/facility/roadGradeList";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        HttpEntity<String> request = new HttpEntity<>(headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        String response = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> roadGradeList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> bridgeGradeItem = new HashMap<>();
                    bridgeGradeItem.put("roadId",item.get("roadId"));
                    bridgeGradeItem.put("roadName",item.get("roadName"));
                    bridgeGradeItem.put("startStake",item.get("startStake"));
                    bridgeGradeItem.put("endStake",item.get("endStake"));
                    bridgeGradeItem.put("roadNameStake",item.get("roadNameStake"));
                    bridgeGradeItem.put("mqi",item.get("mqi"));
                    bridgeGradeItem.put("mqiGrade",item.get("mqiGrade"));
                    roadGradeList.add(bridgeGradeItem);
                }
                appMapper.truncateRoadGradeList();
                appMapper.batchAddRoadGradeList(roadGradeList);
            }
        }
    }

    @Override
    public void autoSyncShowInfoList() {
        String token = getBaiduToken();
        String url = "http://172.31.255.80/ihs/apipartake/v1/maintenance/showInfo";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        String requestBody = "{}";
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, request, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> showInfoList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> showInfoItem = new HashMap<>();
                    showInfoItem.put("projectName",item.get("projectName"));
                    showInfoItem.put("projectTypeName",item.get("projectTypeName"));
                    showInfoItem.put("startTime",item.get("startTime"));
                    showInfoItem.put("finishTime",item.get("finishTime"));
                    showInfoItem.put("inPlan",item.get("inPlan"));
                    showInfoItem.put("planYear",item.get("planYear"));
                    showInfoItem.put("implement",item.get("implement"));
                    showInfoItem.put("budget",item.get("budget"));
                    showInfoItem.put("projectStatus",item.get("projectStatus"));
                    showInfoItem.put("finishInvest",item.get("finishInvest"));
                    showInfoItem.put("investRatio",item.get("investRatio"));
                    showInfoItem.put("assess",item.get("assess"));
                    showInfoList.add(showInfoItem);
                }
                appMapper.truncateShowInfoList();
                appMapper.batchAddShowInfoList(showInfoList);
            }
        }
    }

    @Override
    public void autoSyncShowStructureList() {
        String token = getBaiduToken();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","Bearer " + token);
        String requestBody = "{}";
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
        RestTemplate restTemplate = new RestTemplate();
        String url1 = "http://172.31.255.80/ihs/apipartake/v1/maintenance/showStructureList?structureType=1";
        String url2 = "http://172.31.255.80/ihs/apipartake/v1/maintenance/showStructureList?structureType=2";
        String url3 = "http://172.31.255.80/ihs/apipartake/v1/maintenance/showStructureList?structureType=3";
        String response = restTemplate.postForObject(url1, request, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        int code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> showStructureList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> showStructureItem = new HashMap<>();
                    showStructureItem.put("structureId",item.get("structureId"));
                    showStructureItem.put("structureType",item.get("structureType"));
                    showStructureItem.put("structureName",item.get("structureName"));
                    showStructureItem.put("sectionName",item.get("sectionName"));
                    showStructureItem.put("startStake",item.get("startStake"));
                    showStructureItem.put("centerStake",item.get("centerStake"));
                    showStructureItem.put("endStake",item.get("endStake"));
                    showStructureItem.put("sectionDirection",item.get("sectionDirection"));
                    showStructureItem.put("maintainId",item.get("maintainId"));
                    showStructureList.add(showStructureItem);
                }
                appMapper.truncateShowStructureList();
                appMapper.batchAddShowStructureList(showStructureList);
            }
        }
        response = restTemplate.postForObject(url2, request, String.class);
        jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> showStructureList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> showStructureItem = new HashMap<>();
                    showStructureItem.put("structureId",item.get("structureId"));
                    showStructureItem.put("structureType",item.get("structureType"));
                    showStructureItem.put("structureName",item.get("structureName"));
                    showStructureItem.put("sectionName",item.get("sectionName"));
                    showStructureItem.put("startStake",item.get("startStake"));
                    showStructureItem.put("centerStake",item.get("centerStake"));
                    showStructureItem.put("endStake",item.get("endStake"));
                    showStructureItem.put("sectionDirection",item.get("sectionDirection"));
                    showStructureItem.put("maintainId",item.get("maintainId"));
                    showStructureList.add(showStructureItem);
                }
                appMapper.batchAddShowStructureList(showStructureList);
            }
        }
        response = restTemplate.postForObject(url3, request, String.class);
        jsonObject = JSON.parseObject(response);
        logger.info("Response: " + response);
        code = jsonObject.getInteger("code");
        if(code == 200){
            JSONArray itemArray = jsonObject.getJSONArray("data");
            if(itemArray!= null && itemArray.size()>0){
                List<Map<String,Object>> showStructureList = new ArrayList<>();
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject item = (JSONObject)itemArray.get(i);
                    Map<String,Object> showStructureItem = new HashMap<>();
                    showStructureItem.put("structureId",item.get("structureId"));
                    showStructureItem.put("structureType",item.get("structureType"));
                    showStructureItem.put("structureName",item.get("structureName"));
                    showStructureItem.put("sectionName",item.get("sectionName"));
                    showStructureItem.put("startStake",item.get("startStake"));
                    showStructureItem.put("centerStake",item.get("centerStake"));
                    showStructureItem.put("endStake",item.get("endStake"));
                    showStructureItem.put("sectionDirection",item.get("sectionDirection"));
                    showStructureItem.put("maintainId",item.get("maintainId"));
                    showStructureList.add(showStructureItem);
                }
                appMapper.batchAddShowStructureList(showStructureList);
            }
        }
    }
}
